package com.ivo.quartz;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ivo.biz.PerformanceMon;
import com.ivo.biz.PerformanceMonManager;
import com.ivo.biz.PerformanceService;
import com.ivo.sys.Code;
import com.ivo.sys.CodeService;

/**
 * 
 *
 * @author Minkey Wang
 * @version 2018年2月22日
 */
@Repository
public class ExamLevelQuartz {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Autowired
	private CodeService codeService;
	
    @Autowired
    private PerformanceService performanceService;
    
	@Autowired
	private PerformanceMonManager performanceMonManager;
	
	@Transactional
    @Scheduled(cron = "0 15 6 16 * ? ")//每月16日上午06:15触发
	public void execute() {
		Calendar calendar = Calendar.getInstance(); 
		SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
		String str = sdf.format(calendar.getTime());
		String month = str.substring(0, 7);
		
	    RestTemplate restTemplate = new RestTemplate();
	    Gson googleJson = new Gson();
	    JsonParser parser = new JsonParser();
		
		//同步考试等级
	    logger.info("同步考试等级start");
		String opeurl = "http://10.20.2.188:5680/NewETS/jcom/getLevelAndOpertion";
		String opejson = restTemplate.getForObject(opeurl, String.class);
		JsonArray opeJarray   = parser.parse(opejson).getAsJsonArray();
		List<Operation> jsonOpeList =  googleJson.fromJson(opeJarray, new TypeToken<List<Operation>>() { }.getType());
		for(Operation operation:jsonOpeList){
			PerformanceMon perTemp = performanceService.getPerformanceMon(month,operation.getUser_id());
			if(perTemp!=null){
				Code code= codeService.getCode(operation.getOperation_id());
				if(code!=null && perTemp.getOpe_fk()==null){
					Long id =code.getId(); 
					perTemp.setOpe_fk(id);
				}
				perTemp.setCount(operation.getOtherCount());
				perTemp.setLevel(operation.getLevel());
				if(perTemp.getFactory().equals("CEL")){
					perTemp.setDiscipline(8.0);
					perTemp.setCompatibility(20.0);
				}
				performanceMonManager.save(perTemp);
			}
		}
		logger.info("同步考试等级end");
	}
	


}
